package tech.ihai.spring.sample.upload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.List;

/**
 * @author Adolphus
 * @description TODO
 * @date 2021/12/5 20:26
 */
@Controller
public class UploadController {
    @RequestMapping(value="/upload", method= RequestMethod.POST)
    public @ResponseBody String upload(HttpServletRequest request){
        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i =0; i< files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    String fileName = file.getOriginalFilename().toLowerCase();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(file.getResource().lastModified());

                    if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".gif")){
                        stream = new BufferedOutputStream(new FileOutputStream(new File("E://照片//images",file.getOriginalFilename())));
                    }else if(fileName.endsWith(".mp4") || fileName.endsWith(".avi") || fileName.endsWith(".mpg") || fileName.endsWith(".mpeg") || fileName.endsWith(".mov")){
                        File parent = new File("E://照片//videos//"+calendar.get(Calendar.YEAR));
                        if(!parent.exists()){
                            parent.mkdirs();
                        }
                        stream = new BufferedOutputStream(new FileOutputStream(new File("E://照片//videos//"+calendar.get(Calendar.YEAR),file.getOriginalFilename())));
                    }else{
                        stream = new BufferedOutputStream(new FileOutputStream(new File("E://照片",file.getOriginalFilename())));
                    }
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream =  null;
                    return "You failed to upload " + i + " =>" + e.getMessage();
                }
            } else {
                return "You failed to upload " + i + " becausethe file was empty.";
            }
        }
        return "upload successful";
    }
}
